﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

using Ext.Net;
using BG.Data;
using Kwan.Data;
using BG.Service;

namespace BG.Web.Admin.Room
{
    public partial class Default : UIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                BtnAddClassInfo.Hidden = !permit[0];
                AppendChild.Hidden = !permit[0];
                BtnAddInfo.Hidden = !permit[0];
                Rename.Hidden = !permit[2];
                //btnChangeHot.Hidden = !permit[2];

                BtnDeleteInfo.Hidden = !permit[3];
                Remove.Hidden = !permit[3];
                if (permit[3])
                {
                    List<GridCommand> gridCommand = new List<GridCommand>{
                        ExtHelper.CreateGridCommand("Delete", Icon.Delete, "删除", "删除该条记录")
                    };
                    GridPanel1.ColumnModel.Columns.Add(ExtHelper.CreateCommandColumn(gridCommand));
                }
                ResourceManager1.RegisterIcon(Icon.StopGreen);
                ResourceManager1.RegisterIcon(Icon.StopRed);
            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            SetEditWindow(new VRoom() { Status = 0 });
            EditWindow.Show();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            string[] list = obj.Split(',');
            (TRoom.entityID == list).Delete<TRoom>();
            Store1.DataBind();
        }

        [DirectMethod]
        public void ChangeState(string obj, string NameValue)
        {
            IList<TRoom> list = JSON.Deserialize<IList<TRoom>>(obj);
            if (list.Count > 0)
            {
                CrudManage.ChangeState(list, NameValue);
                Store1.DataBind();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void EditInfo(string EntityID)
        {
            if (!permit[2]) return;
            SetEditWindow((TRoom.entityID == int.Parse(EntityID)).ListFirst<VRoom>());
            EditWindow.Show();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());
            
            //搜索项
            ps.Set("Cid", txtFilter.Text);
            ps.Set("roomNO", txtSearch.Text);

            int pageindex = e.Start / e.Limit;
            Kwan.Data.Region r = new Kwan.Data.Region(pageindex, e.Limit);

            Expression exp = RoomQuery.MakeSearchWhere(ps);
            IList<VRoom> ListView = exp.List<VRoom>(r, new string[] { e.Sort + " " + e.Dir });

            e.Total = new Expression().Count<TRoom>();
            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        protected void SetEditWindow(VRoom tt)
        {
            if (tt.Status == 2) txtStatus.Disabled = true;
            //if (tt.Deposit == 0)
            //{
            //    string xml = Server.MapPath("~/Helper/site.xml");
            //    XmlHelper xmlHelper = new XmlHelper(xml);
            //    tt.Deposit = Convert.ToInt32(xmlHelper.Read("/Root/Deposit", ""));
            //}

            txtID.Text = tt.EntityID.ToString();
            txtCid.SetValue(tt.Cid.ToString(), tt.ClassName);
            txtStatus.SetValue(tt.Status);
            txtReserve.Text = tt.Reserve.ToString();
            txtRoomNO.Text = tt.RoomNO;
            txtDeposit.Text = tt.Deposit.ToString();
            txtPrice.Text = tt.Price.ToString();
            txtHalfPrice.Text = tt.HalfPrice.ToString();
            txtHourPrice.Text = tt.HourPrice.ToString();
            txtIsComputer.Checked = tt.IsComputer;
            txtIsMaQue.Checked = tt.IsMaQue;
            txtNightPrice.Text = tt.NightPrice.ToString();
            txtFloor.Text = tt.Floor;
            txtCreatedDate.Text = tt.CreatedDate.ToString();
        }

        protected void SaveEditWindow(object sender, DirectEventArgs e)
        {
            TRoom tt = Convert.ToInt32(txtID.Text) > 0 ? 
                (TRoom.entityID == Convert.ToInt32(txtID.Text)).ListFirst<TRoom>() : new TRoom();

            tt.Cid = Convert.ToInt32(txtCid.Value);
            tt.RoomNO = txtRoomNO.Text;
            tt.Status = Convert.ToInt32(txtStatus.Value);
            tt.Reserve = Convert.ToInt32(txtReserve.Text);
            tt.Deposit = Convert.ToInt32(txtDeposit.Text);
            tt.Price = Convert.ToInt32(txtPrice.Text);
            tt.HalfPrice = Convert.ToInt32(txtHalfPrice.Text);
            tt.HourPrice = Convert.ToInt32(txtHourPrice.Text);
            tt.Floor = txtFloor.Text;
            tt.CreatedDate = DateTime.Now;
            tt.NightPrice = Convert.ToInt32(txtNightPrice.Text);
            tt.IsComputer = txtIsComputer.Checked;
            tt.IsMaQue = txtIsMaQue.Checked;

            DBContext.Save(tt);
            Store1.DataBind();
            Store1.Dispose();
            EditWindow.Hide();
        }

        [DirectMethod]
        public void InitClassInfo(string EntityID)
        {
            EntityID = string.IsNullOrEmpty(EntityID) ? "0" : EntityID;
            TRoomClass tt = new TRoomClass();
            tt.Pid = Convert.ToInt32(EntityID);
            SetClass(tt);
            ClassWindow.Show();
        }

        [DirectMethod]
        public void SetClassInfo(string EntityID)
        {
            TRoomClass tt = DBContext.Load<TRoomClass>(Convert.ToInt32(EntityID));
            SetClass(tt);
            ClassWindow.Show();
        }

        private void SetClass(TRoomClass tt)
        {
            txtClassID.Text = tt.EntityID.ToString().ToString();
            txtClassNameCN.Text = tt.NameCN;
            txtClassNameEN.Text = tt.NameEN;
            txtClassPid.Text = tt.Pid.ToString();
            txtClassSort.Text = tt.Sort.ToString();
            txtClassPrice.Text = tt.Price.ToString();
            txtClassHalfPrice.Text = tt.HalfPrice.ToString();
            txtClassHourPrice.Text = tt.HourPrice.ToString();
            txtClassNightPrice.Text = tt.NightPrice.ToString();
            txtClassReserve.Text = tt.Reserve.ToString();
        }

        protected void SaveClassForm(object sender, EventArgs e)
        {
            string x = txtClassPid.Text;
            TRoomClass tt = Convert.ToInt32(txtClassID.Text) == 0 ? new TRoomClass() : 
                (TRoomClass.entityID == Convert.ToInt32(txtClassID.Text)).ListFirst<TRoomClass>();
            tt.NameCN = txtClassNameCN.Text;
            tt.NameEN = txtClassNameEN.Text;
            tt.Pid = string.IsNullOrEmpty(txtClassPid.Text) ? 0 : int.Parse(txtClassPid.Text);
            tt.Sort = Convert.ToInt32(txtClassSort.Text);
            tt.Price = Convert.ToInt32(txtClassPrice.Text);
            tt.Reserve = Convert.ToInt32(txtClassReserve.Text);
            tt.HourPrice = Convert.ToInt32(txtClassHourPrice.Text);
            tt.NightPrice = Convert.ToInt32(txtClassNightPrice.Text);
            tt.HalfPrice = Convert.ToInt32(txtClassHalfPrice.Text);
            DBContext.Save(tt);
            ClassWindow.Hide();
            RefreshTree();
        }

        protected void GetExamplesNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID == "root")
            {
                IList<TRoomClass> ClassList = new Expression().List<TRoomClass>();
                if (ClassList.Count > 0)
                {
                    IList<TRoomClass> Parent = ClassList.AsQueryable().Where(a => a.Pid == 0).ToList(); //父节点
                    e.Nodes = CreateTree(ClassList, Parent);
                }

            }
        }

        private TreeNodeCollection CreateTree(IList<TRoomClass> list, IList<TRoomClass> Parent)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);
            foreach (TRoomClass t in Parent)
            {
                TreeNode node = new TreeNode();
                node.Icon = Icon.Report;
                IList<TRoomClass> child = list.AsQueryable().Where(a => a.Pid == t.EntityID).ToList();
                if (child.Count > 0)
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    //node.SingleClickExpand = true;
                    node.Nodes.AddRange(CreateTree(list, child));
                }
                else
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    node.Leaf = true;
                    //node.SingleClickExpand = true;
                }
                nodes.Add(node);
            }
            return nodes;
        }

        protected void RemoteRename(object sender, RemoteRenameEventArgs e)
        {
            e.Accept = true;
            TRoomClass tt = (TRoomClass.entityID == Convert.ToInt32(e.NodeID)).ListFirst<TRoomClass>();
            tt.NameCN = e.NewText;
            DBContext.Save(tt);
        }

        protected void RemoteRemove(object sender, RemoteActionEventArgs e)
        {
            int nodeID = Convert.ToInt32(e.NodeID);
            TRoom tt = (TRoom.cid == nodeID).ListFirst<TRoom>();
            if (tt != null)
            {
                X.Msg.Alert("系统提示", "不能删除有内容的类别！").Show();
            }
            else
            {
                e.Accept = true;
                (TRoomClass.entityID == nodeID).Delete<TRoomClass>();
            }
        }

        protected void RemoteAppend(object sender, RemoteAppendEventArgs e)
        {
            e.Accept = true;
            TRoomClass tt = new TRoomClass();
            tt.NameCN = e.Text;
            tt.Pid = int.Parse(e.ParentNodeID);
            DBContext.Save(tt);
        }

        protected void RemoteMove(object sender, RemoteMoveEventArgs e)
        {
            e.Accept = true;
            (TRoomClass.entityID == Convert.ToInt32(e.NodeID))
                .Edit<TRoomClass>(d => { d.Pid = int.Parse(e.TargetNodeID); });
        }
        [DirectMethod]
        public void RefreshTree()
        {
            txtFilter.Text = "";
            ClassTree.ReloadAsyncNode("root", new JFunction());
            ClassTree.ExpandAll();
            //ClassTree.ReloadAsyncNode("root", new JFunction());
            //ClassTree.ExpandAll();
        }

        //[DirectMethod]
        //public string UploadNews(string EntityID)
        //{
        //    string msg = string.Empty;
        //    using (Cutter imgCutter = new Cutter())
        //    {
        //        imgCutter.DefPath = "Upload\\News\\";
        //        imgCutter.WidthArray = new int[] { 950 };
        //        imgCutter.HeightArray = new int[] { 713 };
        //        imgCutter.PathArray = new string[] { "pNews" };
        //        msg = imgCutter.UploadImage(txtFileUpload.FileContent, string.Empty);
        //        //msg = "{'success':true,'url':'/Upload/News/pNews/" + FileName + "'}";
        //    }
        //    return "/Upload/News/pNews/" + msg;
        //}
    }
}